import axios from "axios";
import md5 from "js-md5";
import * as trade from "../../request/trade";
import { formatList } from "../../utils/auth";
import moment from "moment";
import db from "../../../datastore";
import lang from "../../i18n";

moment.locale("zh-cn");
let msgList = []; // 暂存消息列表
let chatLList = [];

const state = {
  chatVisible: false, // 是否开启聊天
  chatkehuList: [], // 客户聊天记录
  chatkefuList: [], // 客服聊天记录
  srcList: [],
  kid: "",
  uid: "",
  userInfo2: "", // 储存用户信息
  isReconnect: false, // 是否重连
  islogVisible: false, // 异地登录提示
  tradeUrl: "", // 交易线路地址
  token: null, // token数据
  sendinfo: "", // 用户登录发送的数据暂存，用于发送给ws接口
  userinfo: null, // 存储登录信息
  connection: false, // 登录时创建的trade.ws连接
  remname: true, // 记住用户名
  rempwd: true, // 记住用户名
  userip: "1.1.1.1", // 当前用户ip地址
  cpwstu: false, // 用户是否修改密码成功
  messageList: [], // 消息列表
  msgHtml: null, // html消息
  gtyuming: "", //练习、
  setList: [],
  zhibiao: [], //k线指标
};

const mutations = {
  // 客服
  SET_CHATVISIBLE: (state, flag) => {
    state.chatVisible = flag;
  },
  SET_SRCLIST: (state, list) => {
    state.srcList = list;
  },
  SET_ZHIBIAO: (state, list) => {
    state.zhibiao = list;
  },
  SET_CHATKEHULIST: (state, list) => {
    state.chatkehuList = list;
  },
  SET_CHATKEFULIST: (state, list) => {
    state.chatkefuList = list;
  },
  SET_UID: (state, id) => {
    state.uid = id;
  },
  SET_KID: (state, id) => {
    state.kid = id;
    console.log("kid", state.kid);
  },
  SET_USERINFO2: (state, userinfo) => {
    state.userInfo2 = userinfo;
  },
  // 客服
  setList: (state, list) => {
    let _list = JSON.parse(JSON.stringify(list));
    state.setList = _list;
    // console.log('list===', state.setList)
  },
  SET_ISRECONNECT: (state, flag) => {
    state.isReconnect = flag;
  },
  SET_ISLOGVISIBLE: (state, flag) => {
    state.islogVisible = flag;
  },
  SET_MSGHTML: (state, mhtml) => {
    state.msgHtml = mhtml;
  },

  SET_TRADEURL: (state, url) => {
    state.tradeUrl = url;
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_CONNECTION: (state, connection) => {
    state.connection = connection;
  },
  SET_SENDINFO: (state, sendinfo) => {
    state.sendinfo = sendinfo;
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo;
    console.log(state.userinfo);
  },
  SET_REMNAME: (state, iskeep) => {
    state.remname = iskeep;
  },
  SET_REMPWD: (state, iskeep) => {
    state.rempwd = iskeep;
  },
  SET_USERIP: (state, ip) => {
    state.userip = ip;
    console.log("ip", ip);
  },
  SET_CPWSTU: (state, stu) => {
    state.cpwstu = stu;
  },
  SET_MESSAGELIST: (state, list) => {
    state.messageList = list;
  },
  SET_YUMING: (state, gtyuming) => {
    //练习
    state.gtyuming = gtyuming;
  },
};

const actions = {
  updateZhibiao: ({ commit }, data) => {
    commit("SET_ZHIBIAO", data);
  },
  updateChatVisible: ({ commit }, flag) => {
    commit("SET_CHATVISIBLE", flag);
  },
  updateKid: ({ commit }, data) => {
    commit("SET_KID", data);
  },
  updateChatList0: ({ commit }, list) => {
    commit("SET_CHATKEHULIST", list);
    chatLList = list;
    // 获取历史记录中的SET_SRCLIST
    let attlist = [];
    list &&
      list.map((item, i) => {
        let _msg = String(item.msg);

        if (_msg.indexOf("image") != -1) {
          attlist.push(list[i].msg);
        }
      });
    commit("SET_SRCLIST", attlist);
  },
  updateChatList: ({ commit }, list) => {
    let _list = {};
    _list = list.content;
    let arr = chatLList;
    arr.push(_list);
    // console.log(arr, '-', _list)

    commit("SET_CHATKEHULIST", arr); // 客服列表
    localStorage.setItem("chatList", JSON.stringify(arr));
    let attlist = [];
    arr &&
      arr.map((item, i) => {
        let _msg = String(item.msg);
        if (_msg.indexOf("image") != -1) {
          attlist.push(arr[i].msg);
        }
      });
    commit("SET_SRCLIST", attlist); // 储存聊天信息
    console.log(
      "消息内存大小",
      unescape(encodeURIComponent(JSON.stringify(localStorage))).length /
      1024 /
      1024
    );
    if (
      unescape(encodeURIComponent(JSON.stringify(localStorage))).length /
      1024 /
      1024 >
      4.5
    ) {
      // 查看缓存内容容量
      let getItemList = JSON.parse(localStorage.getItem("chatList"));
      getItemList = getItemList.splice(0, 10);
      localStorage.setItem("chatList", JSON.stringify(getItemList));
      let attlist = [];
      getItemList &&
        getItemList.map((item, i) => {
          let _msg = String(item.msg);
          if (_msg.indexOf("image") != -1) {
            attlist.push(getItemList[i].msg);
          }
        });
      commit("SET_SRCLIST", attlist);
    }
  },
  getChatList: ({ commit }, list) => {
    console.log("list", list);
    let _list = [];
    _list = JSON.parse(list).content;
    chatLList = _list;
    console.log("chatkehuList", chatLList);
    commit("SET_CHATKEHULIST", _list);
  },
  // 以上客服
  gettest00: ({ commit }, val) => {
    commit("test00", val);
  },
  // 更新用户合约设置list
  updateSetList: ({ commit }, list) => {
    commit("setList", list);
  },
  // 是否重连
  updateReconnect: ({ commit }, flag) => {
    commit("SET_ISRECONNECT", flag);
  },
  // 是否异地登录提示
  updateLogVisible: ({ commit }, flag) => {
    commit("SET_ISLOGVISIBLE", flag);
  },
  login: ({ commit, state, dispatch, rootGetters }, userInfo) => {
    // 获取url
    let nodeList = db
      .read()
      .get("trades.lineNode")
      .value();
    let loginUrl = nodeList.filter((v) => v.selected)[0];
    let port = db // 获取端口号
      .read()
      .get("trades.port")
      .value();
    let ipurl = db // 获取用户IP
      .read()
      .get("trades.ipUrl")
      .value();
    let _ip = window.ip;
    axios
      .get(`${ipurl}/index.php/index/login/getIp`)
      .then((res) => {
        console.log(res);
        if (res.data) {
          _ip = res.data;
          // 获取到ip 地址,并设置到store中
          const regex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
          if (regex.test(_ip)) {
            commit("SET_USERIP", _ip);
          } else {
            commit("SET_USERIP", '1.1.1.1');
          }
        } else {
          _ip = window.ip;
        }
      })
      .catch(() => {
        _ip = window.ip;
      });
    let plat_bh =
      db
        .read()
        .get("trades.diskType")
        .value() == "1"
        ? "FY"
        : "FM";
    // mnurl
    let loginurl =
      db
        .read()
        .get("trades.diskType")
        .value() == "1"
        ? loginUrl.url
        : loginUrl.mnurl;
    // 用户登录
    const { username, password } = userInfo;
    var moniNode = loginUrl.node.split(":");
    moniNode[2] = moniNode[2].split("/");
    moniNode[2][0] = "8001";
    moniNode[2] = moniNode[2].join("/");
    var mnWsUrl = moniNode.flat(2).join(":");
    let diskType = db
      .read()
      .get("trades.diskType")
      .value();
    var wsNode = diskType == 1 ? loginUrl.node : mnWsUrl;
    axios
      .post(`${loginurl}${port}/index.php/login`, {
        bh: username,
        password: md5(password),
        ploatform: plat_bh,
        mark: "pc",
      })
      .then((res) => {
        if (res.status === 200 && res.data.code === 1) {
          commit("SET_YUMING", res.data.data.gt_yuming); //练习
          commit("SET_UID", res.data.data.uid); // 用户
          commit("SET_USERINFO2", res.data); // 储存用户信息
          var userdata = res.data.data;
          var arr = [
            10,
            1,
            userdata.uid,
            userdata.xingming,
            userdata.suiji_pass,
            userdata.gendan_num,
            userdata.gt_mingcheng,
            userdata.gt_yuming,
            2,
          ];
          if (userdata.rmb) {
            let newArr = [
              1,
              userdata.rmb.yue,
              userdata.rmb.dongjie,
              userdata.rmb.float_yk,
              userdata.rmb.zhunbeijin,
              userdata.rmb.rujin,
              userdata.rmb.chujin,
              userdata.rmb.tiaozheng,
              userdata.rmb.huabo,
              0,
              userdata.rmb.pingcang_yk,
              userdata.rmb.shouxufei,
              userdata.rmb.yanqifei,
              0,
              0,
              userdata.rmb.jian_baozheng,
            ];
            arr = arr.concat(newArr);
          }
          if (userdata.my) {
            let newArr = [
              3,
              userdata.my.yue,
              userdata.my.dongjie,
              userdata.my.float_yk,
              userdata.my.zhunbeijin,
              userdata.my.rujin,
              userdata.my.chujin,
              userdata.my.tiaozheng,
              userdata.my.huabo,
              0,
              userdata.my.pingcang_yk,
              userdata.my.shouxufei,
              userdata.my.yanqifei,
              0,
              0,
              userdata.my.jian_baozheng,
            ];
            arr = arr.concat(newArr);
          }
          dispatch("user/setLogin", arr, { root: true });
          // 初始化连接
          let mqttOption = Object.assign(res.data.data, {
            username: username,
            password: md5(password),
          });
          trade.initWebSocket(
            new Date().getTime(),
            wsNode,
            mqttOption,
            (res) => {
              console.log(res);
            }
          );
        } else {
          dispatch("user/changeTradeStatu", false, { root: true });
          dispatch(
            "bar/changeLoadings",
            {
              status: false,
            },
            { root: true }
          );
          dispatch(
            "bar/switchAlert",
            {
              title: lang[rootGetters.lang].login.lFail,
              msg: res.data.msg,
              type: 3,
            },
            { root: true }
          );
        }
      })
      .catch(() => {
        dispatch(
          "bar/changeLoadings",
          {
            status: false,
          },
          { root: true }
        );
      });
  },
  setLogin: ({ commit, dispatch }, data) => {
    // eslint-disable-next-line no-unused-vars
    // console.log('柜台域名：', data)
    let [
      ,
      ,
      uId,
      uName,
      token,
      documentaryNum,
      counterName,
      counterIP,
      currencyNum,
    ] = data;
    let obj = {
      uId, // 用户ID
      uName, // 姓名
      token, // 随机码
      documentaryNum, // 跟单数量
      counterName, // 柜台名字
      counterIP, // 柜台域名
      currencyNum, // 币种数量
    };
    let nowarr = [
      "currencyId", //  货币ID
      "accountBalance", // 账户余额
      "frozenAmount", // 冻结金额
      "floatPL", // 浮动盈亏
      "lastReserve", // 上次结算准备金
      "deposit", // 今日入金
      "withdrawal", // 今日出金
      "adjustment", // 今日调整
      "transfer", // 今日划拨
      "curConversion", // 今日货币转换
      "liquidatePL", // 平仓盈亏
      "handlingFee", // 手续费
      "deferredFee", // 延期费
      "riskFund", // 风险金
      "overnightRF", // 隔夜风险金
      "occupationMargin", // 占用保证金
    ];
    let currencyList = formatList(data, nowarr, parseInt(currencyNum), 9);
    // console.log(currencyList)
    commit("SET_USERINFO", obj); // 存入用户信息
    dispatch("product/updateCurList", currencyList, {
      root: true,
    }); // 存入货币列表
    dispatch(
      "bar/changeLoadings",
      {
        status: false,
      },
      {
        root: true,
      }
    ); // 关闭loading
    commit("SET_TOKEN", token);
  },
  logout: ({ commit, rootGetters }, iskeep) => {
    // 用户退出登录
    commit("SET_TOKEN", null); // 清除token信息
    commit("SET_USERINFO", null); // 清除用户信息
    // 清除货币列表
    commit("product/SET_MONEYLIST", null, {
      root: true,
    });
    // 清除持仓列表
    commit("panel/SET_POSITIONLIST", [], {
      root: true,
    });
    // 清空委托单列表
    commit("panel/SET_COMMISSIONLIST", [], {
      root: true,
    });

    if (!iskeep) {
      commit("panel/SET_SPANEL", false, {
        root: true,
      }); // 关闭交易面板
    }

    // 断开websock连接
    trade.wsClose();
  },
  changeTradeStatu: ({ commit }, status) => {
    // 设置交易websock连接状态
    commit("SET_CONNECTION", status);
  },
  keepInMind: ({ commit, state }, keepinfo) => {
    let { type, val } = keepinfo;
    if (type === "1" && state.remname !== val) {
      commit("SET_REMNAME", val);
    }

    if (type === "2" && state.rempwd !== val) {
      commit("SET_REMPWD", val);
    }
  },
  changeLogin: () => {
    commit("product/SET_MONEYLIST", null, {
      root: true,
    }); // 清除货币列表
  },
  // 用户修改密码
  changePwStu: ({ commit, dispatch }, status) => {
    commit("SET_CPWSTU", status);
  },
  // 更新交易地址
  updateTradeUrl: ({ commit }, url) => {
    commit("SET_TRADEURL", url);
  },
  updateMsgList: ({ commit }, msg) => {
    // console.log(msg)
    if (msg[1] === "5") {
      msgList = [];
      commit("SET_MESSAGELIST", []);
      // console.log('总数：' + plist[2])
      return;
    }
    // 36;1;消息ID;标题;时间（unix时间戳）;浏览标志;
    let [, , MsgID, Title, Time, Sign] = msg;
    if (MsgID === "0") {
      commit("SET_MESSAGELIST", msgList);
    } else {
      if (Time && Time !== "0") {
        Time = moment(Time * 1000).format("YYYY-MM-DD HH:mm");
      }
      let obj = {
        MsgID, // 消息ID
        Title, // 标题
        timestamp: Time,
        DateTime: Time, // 时间
        Sign, // 浏览标志
      };
      // 推入暂存数组
      msgList.push(obj);
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
